package com.pandy.transaction;

import java.sql.*;

/**
 * @description: JDBC事务管理
 * @author: panhong
 * @date: 2025/3/19
 */
public class JDBCMain {
    public static void main(String[] args) throws SQLException {
        Statement stmt = null;
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String sql = "insert into user values(null,'zs',25)";
            conn = DriverManager.getConnection("jdbc:mysql://192.168.5.129:3306/btest_engine",
                    "root", "PandySmile123!");
            stmt = conn.createStatement();

            // 开启事务
            conn.setAutoCommit(false);

            int count = stmt.executeUpdate(sql);//影响的行数

            // 模拟异常
            int i = 1 / 0;

            // 提交事务
            conn.commit();
            System.out.println(count);
            if(count > 0){
                System.out.println("添加成功！");
            }else{
                System.out.println("添加失败！");
            }
        } catch (Exception e) {
            // 回滚事务
            conn.rollback();
            e.printStackTrace();
        } finally {

            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
